<!DOCTYPE html>
<html lang="zh-Hans">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 3.8.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"yoursite.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="基础Java8 新特性https://www.cnblogs.com/dzy521/p/10077132.html Stream由于Stream的起始点是基于Array来初始化，集合List可以直接通过parallelStream方法来启动一个Stream flatMap vs map前者在结构之后是直接返回被扁平后的流对象，后者还是返回包装好原来元素的流对象 java8注解新特性 增加二个注解类">
<meta name="keywords" content="Java">
<meta property="og:type" content="article">
<meta property="og:title" content="Java系列之零碎笔记">
<meta property="og:url" content="http://yoursite.com/2019/11/30/Java系列之零碎笔记/index.html">
<meta property="og:site_name" content="Feng&#39;s Blog">
<meta property="og:description" content="基础Java8 新特性https://www.cnblogs.com/dzy521/p/10077132.html Stream由于Stream的起始点是基于Array来初始化，集合List可以直接通过parallelStream方法来启动一个Stream flatMap vs map前者在结构之后是直接返回被扁平后的流对象，后者还是返回包装好原来元素的流对象 java8注解新特性 增加二个注解类">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://gitee.com/fengorz/oss/raw/master/uPic/FIG9fa.png">
<meta property="og:image" content="https://gitee.com/fengorz/oss/raw/master/uPic/36r68I.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/coding-by-feng/oss@master/uPic/xLpjyO.png">
<meta property="og:updated_time" content="2020-09-08T09:54:45.713Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Java系列之零碎笔记">
<meta name="twitter:description" content="基础Java8 新特性https://www.cnblogs.com/dzy521/p/10077132.html Stream由于Stream的起始点是基于Array来初始化，集合List可以直接通过parallelStream方法来启动一个Stream flatMap vs map前者在结构之后是直接返回被扁平后的流对象，后者还是返回包装好原来元素的流对象 java8注解新特性 增加二个注解类">
<meta name="twitter:image" content="https://gitee.com/fengorz/oss/raw/master/uPic/FIG9fa.png">

<link rel="canonical" href="http://yoursite.com/2019/11/30/Java系列之零碎笔记/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-Hans'
  };
</script>

  <title>Java系列之零碎笔记 | Feng's Blog</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Feng's Blog</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-Hans">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/11/30/Java系列之零碎笔记/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="Fengorz">
      <meta itemprop="description" content="A Quiet Departure.">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Feng's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Java系列之零碎笔记
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2019-11-30 21:12:21" itemprop="dateCreated datePublished" datetime="2019-11-30T21:12:21+08:00">2019-11-30</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2020-09-08 17:54:45" itemprop="dateModified" datetime="2020-09-08T17:54:45+08:00">2020-09-08</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Java/" itemprop="url" rel="index"><span itemprop="name">Java</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="基础"><a href="#基础" class="headerlink" title="基础"></a>基础</h1><h2 id="Java8-新特性"><a href="#Java8-新特性" class="headerlink" title="Java8 新特性"></a>Java8 新特性</h2><p><a href="https://www.cnblogs.com/dzy521/p/10077132.html" target="_blank" rel="noopener">https://www.cnblogs.com/dzy521/p/10077132.html</a></p>
<h3 id="Stream"><a href="#Stream" class="headerlink" title="Stream"></a>Stream</h3><p>由于Stream的起始点是基于Array来初始化，集合List可以直接通过parallelStream方法来启动一个Stream</p>
<h4 id="flatMap-vs-map"><a href="#flatMap-vs-map" class="headerlink" title="flatMap vs map"></a>flatMap vs map</h4><p>前者在结构之后是直接返回被扁平后的流对象，后者还是返回包装好原来元素的流对象</p>
<h3 id="java8注解新特性"><a href="#java8注解新特性" class="headerlink" title="java8注解新特性"></a>java8注解新特性</h3><ol>
<li>增加二个注解类型（ElementType.TYPE_USE 和 ElementType.TYPE_PARAMETER）<br> 意思是可以声明在任何类型声明的地方，比如lombok的@NonNull的几个用例：<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">@NonNull String str;</span><br></pre></td></tr></table></figure>
</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">@NonNull List&lt;String&gt;</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">// 非负数</span><br><span class="line">Arrays&lt;@NonNegative Integer&gt; sort</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">@Encrypted File file</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">void divideInteger(int a, int b) throws @ZeroDivisor ArithmeticException</span><br></pre></td></tr></table></figure>
<ol>
<li>允许重复注解</li>
</ol>
<h3 id="参数名称的反射获取"><a href="#参数名称的反射获取" class="headerlink" title="参数名称的反射获取"></a>参数名称的反射获取</h3><p>Java 8终于将这个特性规范化，在语言层面（使用反射API和Parameter.getName()方法）和字节码层面（使用新的javac编译器以及-parameters参数）提供支持.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public static void main(String[] args) &#123;</span><br><span class="line">&#125;</span><br><span class="line">@Test</span><br><span class="line">@SneakyThrows</span><br><span class="line">public void test1() &#123;</span><br><span class="line">    Method method = GeneratorTest.class.getMethod(&quot;main&quot;, String[].class);</span><br><span class="line">    for (Parameter parameter : method.getParameters()) &#123;</span><br><span class="line">        System.out.println(parameter.getName());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>打印结果为：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">args</span><br></pre></td></tr></table></figure></p>
<h3 id="Iterable-forEach"><a href="#Iterable-forEach" class="headerlink" title="Iterable.forEach"></a>Iterable.forEach</h3><p>在逻辑稍微复杂一旦的循环体里面不建议使用，至少要在外部方法声明处抛出个异常都不行，简单的循环可以使用。</p>
<h3 id="FunctionalInterface（函数式接口）"><a href="#FunctionalInterface（函数式接口）" class="headerlink" title="@FunctionalInterface（函数式接口）"></a>@FunctionalInterface（函数式接口）</h3><p><a href="http://www.manongjc.com/article/46188.html" target="_blank" rel="noopener">http://www.manongjc.com/article/46188.html</a></p>
<h3 id="parallelStream-vs-stream"><a href="#parallelStream-vs-stream" class="headerlink" title="parallelStream() vs stream()"></a>parallelStream() vs stream()</h3><p>前者是并行执行流，如果对执行结果的顺序没有要求，建议使用并行执行的parallelStream()，可以提高流执行的性能。</p>
<h2 id="关键字"><a href="#关键字" class="headerlink" title="关键字"></a>关键字</h2><h3 id="transient"><a href="#transient" class="headerlink" title="transient"></a>transient</h3><p><a href="https://baijiahao.baidu.com/s?id=1636557218432721275&amp;wfr=spider&amp;for=pc" target="_blank" rel="noopener">https://baijiahao.baidu.com/s?id=1636557218432721275&amp;wfr=spider&amp;for=pc</a></p>
<h3 id="Class"><a href="#Class" class="headerlink" title="Class"></a>Class</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">void.class // 罕见又骚气的用法</span><br></pre></td></tr></table></figure>
<h2 id="泛型"><a href="#泛型" class="headerlink" title="泛型"></a>泛型</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public &lt;T&gt; T readObjectData(ByteBuffer buffer, Class&lt;T&gt; type) &#123;</span><br><span class="line">...</span><br><span class="line">T retVal = (T) summaries;</span><br><span class="line">return retVal;</span><br></pre></td></tr></table></figure>
<p>我在stackoverflow发现一个很好的解析：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">public &lt;T&gt; T readObjectData(...</span><br><span class="line">        ^  ^</span><br><span class="line">        |  + Return type</span><br><span class="line">        + Generic type argument</span><br></pre></td></tr></table></figure></p>
<h2 id="集合"><a href="#集合" class="headerlink" title="集合"></a>集合</h2><h3 id="Unimagined"><a href="#Unimagined" class="headerlink" title="Unimagined"></a>Unimagined</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">// 一个集合并入到另一个集合的安全写法</span><br><span class="line">Collections.addAll(Collection&lt;? super T&gt; c, T... elements);</span><br></pre></td></tr></table></figure>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Collections.singletonMap(...);</span><br></pre></td></tr></table></figure>
<h3 id="快速失败机制（fast-fail）"><a href="#快速失败机制（fast-fail）" class="headerlink" title="快速失败机制（fast-fail）"></a>快速失败机制（fast-fail）</h3><p>集合常见的快速失败检查都是通过如下代码：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">final void checkForComodification() &#123;</span><br><span class="line">    if (modCount != expectedModCount)</span><br><span class="line">        throw new ConcurrentModificationException();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h3 id="来自网上的Java集合体系图"><a href="#来自网上的Java集合体系图" class="headerlink" title="来自网上的Java集合体系图"></a>来自网上的Java集合体系图</h3><p><img src="https://gitee.com/fengorz/oss/raw/master/uPic/FIG9fa.png" alt><br><img src="https://gitee.com/fengorz/oss/raw/master/uPic/36r68I.png" alt></p>
<h2 id="异常"><a href="#异常" class="headerlink" title="异常"></a>异常</h2><h3 id="一些自定义常用异常可以抽成公用的静态final异常，如："><a href="#一些自定义常用异常可以抽成公用的静态final异常，如：" class="headerlink" title="一些自定义常用异常可以抽成公用的静态final异常，如："></a>一些自定义常用异常可以抽成公用的静态final异常，如：</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">public final class PrematureCloseException extends IOException &#123;</span><br><span class="line"></span><br><span class="line">	public static final PrematureCloseException BEFORE_RESPONSE_SENDING_REQUEST =</span><br><span class="line">			new PrematureCloseException(&quot;Connection has been closed BEFORE response, while sending request body&quot;);</span><br><span class="line"></span><br><span class="line">	public static final PrematureCloseException BEFORE_RESPONSE =</span><br><span class="line">			new PrematureCloseException(&quot;Connection prematurely closed BEFORE response&quot;);</span><br><span class="line"></span><br><span class="line">	public static final PrematureCloseException DURING_RESPONSE =</span><br><span class="line">			new PrematureCloseException(&quot;Connection prematurely closed DURING response&quot;);</span><br><span class="line"></span><br><span class="line">	PrematureCloseException(String message) &#123;</span><br><span class="line">		super(message);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	@Override</span><br><span class="line">	public synchronized Throwable fillInStackTrace() &#123;</span><br><span class="line">		// omit stacktrace for this exception</span><br><span class="line">		return this;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="一些运行时异常可以用Spring内置的断言API比较高逼格"><a href="#一些运行时异常可以用Spring内置的断言API比较高逼格" class="headerlink" title="一些运行时异常可以用Spring内置的断言API比较高逼格"></a>一些运行时异常可以用Spring内置的断言API比较高逼格</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Assert.notNull etc.</span><br></pre></td></tr></table></figure>
<h2 id="非null判断的优雅写法"><a href="#非null判断的优雅写法" class="headerlink" title="非null判断的优雅写法"></a>非null判断的优雅写法</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Objects.requireNonNull(obj);</span><br></pre></td></tr></table></figure>
<h2 id="try资源句式"><a href="#try资源句式" class="headerlink" title="try资源句式"></a>try资源句式</h2><p>如果代码调用的类是实现java.lang.AutoCloseable的，用try资源句式来释放关闭资源这样代码就优雅多了。</p>
<h2 id="PropertyDescriptor"><a href="#PropertyDescriptor" class="headerlink" title="PropertyDescriptor"></a>PropertyDescriptor</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">PropertyDescriptor descriptor = new PropertyDescriptor(&quot;propertyName&quot;, param.getClass());</span><br><span class="line">Method getPropertyMethod = descriptor.getReadMethod();</span><br><span class="line">property = (Integer) getPropertyMethod.invoke(param);</span><br></pre></td></tr></table></figure>
<h2 id="String"><a href="#String" class="headerlink" title="String"></a>String</h2><h3 id="String-format"><a href="#String-format" class="headerlink" title="String.format"></a>String.format</h3><p><a href="https://blog.csdn.net/u010137760/article/details/82869637" target="_blank" rel="noopener">https://blog.csdn.net/u010137760/article/details/82869637</a></p>
<h3 id="String-intern"><a href="#String-intern" class="headerlink" title="String.intern"></a>String.intern</h3><p><a href="https://www.cnblogs.com/Yintianhao/p/12273714.html" target="_blank" rel="noopener">https://www.cnblogs.com/Yintianhao/p/12273714.html</a></p>
<hr>
<h1 id="避坑"><a href="#避坑" class="headerlink" title="避坑"></a>避坑</h1><h2 id="代码格式"><a href="#代码格式" class="headerlink" title="代码格式"></a>代码格式</h2><p>一个团队你的代码格式一定要统一，不然代码冲突时，比对代码非常麻烦。</p>
<h2 id="Service与Controller的交互"><a href="#Service与Controller的交互" class="headerlink" title="Service与Controller的交互"></a>Service与Controller的交互</h2><p>Service最终返回给Controller层的数据如果比较复杂，尽量不要用Map，可以封装成DTO，而且这样一来还可以结合JSR303或者其各种扩展，对DTO进行优雅的数据校验。</p>
<h2 id="减少箭头型代码"><a href="#减少箭头型代码" class="headerlink" title="减少箭头型代码"></a>减少箭头型代码</h2><p><a href="https://blog.csdn.net/weixin_33858485/article/details/88768985" target="_blank" rel="noopener">https://blog.csdn.net/weixin_33858485/article/details/88768985</a><br>但是个人认为，一味的追求箭头代码也会有弊端，比如这样:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">Task task = monTask.getTask();</span><br><span class="line">if (task == null) &#123;</span><br><span class="line">    return;</span><br><span class="line">&#125;</span><br><span class="line">MonAssignTaskExample monAssignTaskExample = new MonAssignTaskExample();</span><br><span class="line">monAssignTaskExample.createCriteria().andTaskIdEqualTo(task.getTaskId()).andDealObjectIdEqualTo(task.getDealObjectId())</span><br><span class="line">        .andIsFinishEqualTo(&quot;N&quot;);</span><br><span class="line">List&lt;MonAssignTask&gt; monAssignTasks = this.baseMonAssignTaskBO.selectByExample(monAssignTaskExample);</span><br><span class="line">if (ObjectUtils.isEmpty(monAssignTasks)) &#123;</span><br><span class="line">    return;</span><br><span class="line">&#125;</span><br><span class="line">for (MonAssignTask monAssignTask : monAssignTasks) &#123;</span><br><span class="line">    // do something</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这样写固然是可以减少箭头代码，但是如若这段代码下面今后要添加一些额外的业务逻辑，这些业务逻辑与task是否为null没有必要的联系，<br>那么可能会因为task==null退出了整个函数，导致额外的业务逻辑不被执行。</p>
<h2 id="Utils-工具类的命名"><a href="#Utils-工具类的命名" class="headerlink" title="Utils 工具类的命名"></a>Utils 工具类的命名</h2><p>每次在使用工具类的时候，总是会出现一个类名出现N个工具类比如：<br><img src="https://cdn.jsdelivr.net/gh/coding-by-feng/oss@master/uPic/xLpjyO.png" alt="image"><br>而且自己也会有自定义的Utils类，为了更好地区分，我喜欢在Utils类价格前缀Enhanced，这样找自己的工具类就方便多了，比如：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">EnhancedBeanUtils</span><br></pre></td></tr></table></figure></p>
<h2 id="Deprecated"><a href="#Deprecated" class="headerlink" title="@Deprecated"></a>@Deprecated</h2><p>有些被封装的业务方法或者工具类方法如果有做修改，增加了方法的升级版，老旧的方法可以用@Deprecated标记为过时，防止新业务逻辑用到废弃的API。</p>
<h2 id="魔法值应该尽量避免"><a href="#魔法值应该尽量避免" class="headerlink" title="魔法值应该尽量避免"></a>魔法值应该尽量避免</h2><p>阿里巴巴说java规范里面说杜绝一切魔法值，但是我觉得也不用可以完全追求零魔法值，我认为需要用常量代替魔法值的有以下这些：</p>
<ol>
<li>使用频率高的，或者被频繁调用的逻辑块中的魔法值。</li>
<li>可读性很差的魔法值和表达式，应该禁止，最好都声明成可读性较好的常量或者变量。</li>
</ol>
<h2 id="多余的super"><a href="#多余的super" class="headerlink" title="多余的super();"></a>多余的super();</h2><p>在看公司的上古代码发现这种写法：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">public CreateRepairBillThread(SaInterfaceAccept accept) &#123;</span><br><span class="line">	super();</span><br><span class="line">	this.accept = accept;</span><br><span class="line">	this.timeout = timeout * 60L * 1000L;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这里面super();是一句多余的代码，因为子类的构造器会默认先调用父类无参构造器。</p>
<hr>
<h1 id="Combo"><a href="#Combo" class="headerlink" title="Combo"></a>Combo</h1><h2 id="过时类的坑"><a href="#过时类的坑" class="headerlink" title="过时类的坑"></a>过时类的坑</h2><p>从eclipse迁移到idea之后在本地跑服务的时候，反射调用方法老旧的代码遇到一个巨坑，抛出异常是wrong number of arguments。</p>
<p>根据网上的方法，将invoke方法的入参中数组转为Object都不行，折腾了半天，发现代码中抛出了一个过时的异常，我突发奇想，将这个过时的异常类去掉，结果run success了，真的是惨痛的教训，过时的类和方法，能不用，千万别用。下面上代码：<br>报错代码：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">public static Object invoke(Object obj, String methodName, Object[] params) throws Exception &#123;</span><br><span class="line">		Method method = methodByName(obj.getClass(), methodName);</span><br><span class="line">    	if (method == null)</span><br><span class="line">    		method = methodByName(obj.getClass().getSuperclass(), methodName);</span><br><span class="line">    	if (method != null) &#123;</span><br><span class="line">    		return method.invoke(obj, params);</span><br><span class="line">    	&#125; else &#123;</span><br><span class="line">    		throw new MethodNotFoundException(methodName);</span><br><span class="line">    	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>修改后的代码:<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">public static Object invoke(Object obj, String methodName, Object[] params) throws InvocationTargetException, IllegalAccessException, BOException &#123;</span><br><span class="line">   Method method = methodByName(obj.getClass(), methodName);</span><br><span class="line">       if (method == null)</span><br><span class="line">          method = methodByName(obj.getClass().getSuperclass(), methodName);</span><br><span class="line">       if (method != null) &#123;</span><br><span class="line">          return method.invoke(obj, params);</span><br><span class="line">       &#125; else &#123;</span><br><span class="line">          //之前抛出的异常已经过时，在jdk新版本环境会报错，优化了一下。</span><br><span class="line">          throw new BOException(&quot;方法&quot;+methodName+&quot;没找到&quot;);</span><br><span class="line">       &#125;</span><br><span class="line">&#125;`</span><br></pre></td></tr></table></figure></p>
<h2 id="jar"><a href="#jar" class="headerlink" title="jar"></a>jar</h2><h3 id="Mac中jar运行之后窗口无法粘贴"><a href="#Mac中jar运行之后窗口无法粘贴" class="headerlink" title="Mac中jar运行之后窗口无法粘贴"></a>Mac中jar运行之后窗口无法粘贴</h3><p>有些情况下需要使用windows的复制粘贴快捷键才能生效</p>
<h3 id="jar指定目录的所有classes去打包"><a href="#jar指定目录的所有classes去打包" class="headerlink" title="jar指定目录的所有classes去打包"></a>jar指定目录的所有classes去打包</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">jar cvf test.jar -C unwoven-classes .</span><br></pre></td></tr></table></figure>
<h2 id="Jackson-Convert-Error-Cannot-construct-instance-of-java-time-LocalDateTime"><a href="#Jackson-Convert-Error-Cannot-construct-instance-of-java-time-LocalDateTime" class="headerlink" title="Jackson Convert Error: Cannot construct instance of java.time.LocalDateTime"></a>Jackson Convert Error: Cannot construct instance of <code>java.time.LocalDateTime</code></h2><p>LocalDateTime属性加上注解<br>@JsonDeserialize(using = LocalDateTimeDeserializer.class)<br>@JsonSerialize(using = LocalDateTimeSerializer.class)</p>
<h2 id="Thread-sleep-使用-TimeUnit-XXX-sleep-x-代替（可读性更好）"><a href="#Thread-sleep-使用-TimeUnit-XXX-sleep-x-代替（可读性更好）" class="headerlink" title="Thread.sleep 使用 TimeUnit.XXX.sleep(x) 代替（可读性更好）"></a>Thread.sleep 使用 TimeUnit.XXX.sleep(x) 代替（可读性更好）</h2><p><a href="https://stackoverflow.com/questions/9587673/thread-sleep-vs-timeunit-seconds-sleep" target="_blank" rel="noopener">https://stackoverflow.com/questions/9587673/thread-sleep-vs-timeunit-seconds-sleep</a></p>
<h2 id="音频格式转换"><a href="#音频格式转换" class="headerlink" title="音频格式转换"></a>音频格式转换</h2><p>使用<a href="http://www.sauronsoftware.it/projects/jave/manual.php#2" target="_blank" rel="noopener">JAVE 音频转换包</a>库</p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/Java/" rel="tag"># Java</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2019/11/30/English之句型结构系列/" rel="prev" title="English之句型结构系列">
      <i class="fa fa-chevron-left"></i> English之句型结构系列
    </a></div>
      <div class="post-nav-item">
    <a href="/2019/12/01/Idea汇总/" rel="next" title="Idea汇总">
      Idea汇总 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#基础"><span class="nav-number">1.</span> <span class="nav-text">基础</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Java8-新特性"><span class="nav-number">1.1.</span> <span class="nav-text">Java8 新特性</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Stream"><span class="nav-number">1.1.1.</span> <span class="nav-text">Stream</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#flatMap-vs-map"><span class="nav-number">1.1.1.1.</span> <span class="nav-text">flatMap vs map</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#java8注解新特性"><span class="nav-number">1.1.2.</span> <span class="nav-text">java8注解新特性</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#参数名称的反射获取"><span class="nav-number">1.1.3.</span> <span class="nav-text">参数名称的反射获取</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Iterable-forEach"><span class="nav-number">1.1.4.</span> <span class="nav-text">Iterable.forEach</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#FunctionalInterface（函数式接口）"><span class="nav-number">1.1.5.</span> <span class="nav-text">@FunctionalInterface（函数式接口）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#parallelStream-vs-stream"><span class="nav-number">1.1.6.</span> <span class="nav-text">parallelStream() vs stream()</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#关键字"><span class="nav-number">1.2.</span> <span class="nav-text">关键字</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#transient"><span class="nav-number">1.2.1.</span> <span class="nav-text">transient</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Class"><span class="nav-number">1.2.2.</span> <span class="nav-text">Class</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#泛型"><span class="nav-number">1.3.</span> <span class="nav-text">泛型</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#集合"><span class="nav-number">1.4.</span> <span class="nav-text">集合</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Unimagined"><span class="nav-number">1.4.1.</span> <span class="nav-text">Unimagined</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#快速失败机制（fast-fail）"><span class="nav-number">1.4.2.</span> <span class="nav-text">快速失败机制（fast-fail）</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#来自网上的Java集合体系图"><span class="nav-number">1.4.3.</span> <span class="nav-text">来自网上的Java集合体系图</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#异常"><span class="nav-number">1.5.</span> <span class="nav-text">异常</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#一些自定义常用异常可以抽成公用的静态final异常，如："><span class="nav-number">1.5.1.</span> <span class="nav-text">一些自定义常用异常可以抽成公用的静态final异常，如：</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#一些运行时异常可以用Spring内置的断言API比较高逼格"><span class="nav-number">1.5.2.</span> <span class="nav-text">一些运行时异常可以用Spring内置的断言API比较高逼格</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#非null判断的优雅写法"><span class="nav-number">1.6.</span> <span class="nav-text">非null判断的优雅写法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#try资源句式"><span class="nav-number">1.7.</span> <span class="nav-text">try资源句式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#PropertyDescriptor"><span class="nav-number">1.8.</span> <span class="nav-text">PropertyDescriptor</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#String"><span class="nav-number">1.9.</span> <span class="nav-text">String</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#String-format"><span class="nav-number">1.9.1.</span> <span class="nav-text">String.format</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#String-intern"><span class="nav-number">1.9.2.</span> <span class="nav-text">String.intern</span></a></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#避坑"><span class="nav-number">2.</span> <span class="nav-text">避坑</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#代码格式"><span class="nav-number">2.1.</span> <span class="nav-text">代码格式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Service与Controller的交互"><span class="nav-number">2.2.</span> <span class="nav-text">Service与Controller的交互</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#减少箭头型代码"><span class="nav-number">2.3.</span> <span class="nav-text">减少箭头型代码</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Utils-工具类的命名"><span class="nav-number">2.4.</span> <span class="nav-text">Utils 工具类的命名</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Deprecated"><span class="nav-number">2.5.</span> <span class="nav-text">@Deprecated</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#魔法值应该尽量避免"><span class="nav-number">2.6.</span> <span class="nav-text">魔法值应该尽量避免</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#多余的super"><span class="nav-number">2.7.</span> <span class="nav-text">多余的super();</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Combo"><span class="nav-number">3.</span> <span class="nav-text">Combo</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#过时类的坑"><span class="nav-number">3.1.</span> <span class="nav-text">过时类的坑</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#jar"><span class="nav-number">3.2.</span> <span class="nav-text">jar</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Mac中jar运行之后窗口无法粘贴"><span class="nav-number">3.2.1.</span> <span class="nav-text">Mac中jar运行之后窗口无法粘贴</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#jar指定目录的所有classes去打包"><span class="nav-number">3.2.2.</span> <span class="nav-text">jar指定目录的所有classes去打包</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Jackson-Convert-Error-Cannot-construct-instance-of-java-time-LocalDateTime"><span class="nav-number">3.3.</span> <span class="nav-text">Jackson Convert Error: Cannot construct instance of java.time.LocalDateTime</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Thread-sleep-使用-TimeUnit-XXX-sleep-x-代替（可读性更好）"><span class="nav-number">3.4.</span> <span class="nav-text">Thread.sleep 使用 TimeUnit.XXX.sleep(x) 代替（可读性更好）</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#音频格式转换"><span class="nav-number">3.5.</span> <span class="nav-text">音频格式转换</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">Fengorz</p>
  <div class="site-description" itemprop="description">A Quiet Departure.</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">125</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">68</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">87</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Fengorz</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>
<script src="/js/utils.js"></script><script src="/js/motion.js"></script>
<script src="/js/schemes/pisces.js"></script>
<script src="/js/next-boot.js"></script>



  















  

  

</body>
</html>
